import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;

import java.io.FileInputStream;

public class AudioUtils {
    /**
     * 获取音频文件的持续时间。
     *
     * @param filePath 音频文件的路径
     * @return 音频文件的持续时间，单位为秒。如果无法解析文件或获取持续时间信息，则返回默认值0.0。
     */
    public static double getAudioDuration(String filePath) {
        double duration = 0.0;
        try {
            BodyContentHandler handler = new BodyContentHandler();
            Metadata metadata = new Metadata();
            FileInputStream inputStream = new FileInputStream(filePath);
            ParseContext context = new ParseContext();

            AutoDetectParser parser = new AutoDetectParser();
            parser.parse(inputStream, handler, metadata, context);

            String durationString = metadata.get("xmpDM:duration");
            if (durationString != null) {
                duration = Double.parseDouble(durationString) - 1;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return duration;
    }
}